package com.sxpi.user.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022-08-26$ 11:57$
 *
 * 传递token的一种方案
 *
 *
 */
@Component
public class FeginInterceptor implements RequestInterceptor {

    /**
     * feign 调用丢失token解决方案，新增拦截器
     *
     * @return
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            if (request == null){
                return;
            } else {
                String token = request.getHeader("token");
                if (token != null) {
                    requestTemplate.header("token", token);
                }
            }
        }
    }
}
